package com.atguigu.edu.controller;


import com.atguigu.edu.client.VodClient;
import com.atguigu.edu.entity.Video;
import com.atguigu.edu.service.VideoService;
import com.atguigu.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 课程视频 前端控制器
 * </p>
 *
 * @author admin
 * @since 2020-07-06
 */
@RestController
@RequestMapping("/edu/video")
@Api(description = "课程小节/视频-8001")
@Slf4j
public class VideoController {

    @Autowired
    VideoService videoService;

    @ApiOperation(value = "课程小节查询 按小节id查询")
    @GetMapping("/getVideo/{id}")
    public R getVideo(@PathVariable String id) {
        try {
            Video video = videoService.getById(id);
            return R.ok().data("video", video);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
    }

    @Autowired
    VodClient vodClient;

    @ApiOperation(value = "课程小节删除 按小节id删除")
    @DeleteMapping("/delVideo/{id}")
    public R deleteVideo(@PathVariable String id) {
        try {
            Video video = videoService.getById(id);
            if (video != null) {
                String id1 = video.getVideoSourceId();
                if (!StringUtils.isEmpty(id1)) {
                    vodClient.delVideo(id1);
                    log.info("课程视频删除!");
                }
            }

            boolean b = videoService.removeById(id);

            if (b) {
                return R.ok();
            } else {
                return R.error();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.error().message(e.getMessage());
        }

    }

    @ApiOperation(value = "课程小节修改 按小节实体修改")
    @PutMapping("/editVideo")
    public R editVideo(@RequestBody Video video) {

        try {
            boolean b = videoService.updateById(video);
            if (b) {
                return R.ok();
            } else {
                return R.error();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
    }

    @ApiOperation(value = "课程小节添加 按小节实体添加")
    @PostMapping("/saveVideo")
    public R saveVideo(@RequestBody Video video) {
        try {
            boolean b = videoService.save(video);
            if (b) {
                return R.ok();
            } else {
                return R.error();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
    }
}

